package com.eipc;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.androidpn.sdk.Constants;
import org.json.JSONObject;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;

import com.eipc.info.R;
import com.eipc.model.Department;
import com.eipc.model.Position;
import com.eipc.model.SerInfoResponse;
import com.eipc.model.Staff;
import com.eipc.model.Version;
import com.eipc.util.DBHelper;
import com.eipc.util.HttpManager;
import com.eipc.util.Pref;
import com.eipc.util.Tools;

public class FetchPersonService extends Service {

	private DBHelper mDB;
	 
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		// mDB = new DBHelper(this);
		mDB = DBHelper.getInstance(this);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		new PollingTask().execute();
		Log.e("-----------do FetchPersonService-----------------", Tools
				.getCurrentTimeString());

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	class PollingTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			try {
				SharedPreferences sdkPreferences = getSharedPreferences(
						Constants.SDK_PREFERENCES, Context.MODE_PRIVATE);
				String mobileID = sdkPreferences.getString(
						Constants.XMPP_USERNAME, "");

				// 获取版本信息，看是否需要更新，包括Home，桌面，联系人
				SerInfoResponse versionSir = HttpManager.execSerSql2(
						getString(R.string.url_exec_serSql), mobileID,
						"versionsql", Constants.LOAD_MODEL_VERSION);
				if (versionSir == null) {
					return null;
				}
				Version version = (Version) versionSir.os[0];

				Map<String, Integer> versionMap = mDB.queryVersion();
				int contactVersion = 0;
				if (versionMap.get(Pref.KEY_CONTACT) != null) {
					contactVersion = versionMap.get(Pref.KEY_CONTACT);
				}
				if (version.contactVersion > contactVersion) {

					// 联系人
					SerInfoResponse staffSir = HttpManager.execSerSql2(
							getString(R.string.url_exec_serSql), mobileID,
							"staffsql", Constants.LOAD_MODEL_STAFF);
					if (staffSir != null) {
						Staff[] staffs = (Staff[]) staffSir.os;

						mDB.insertStaff(staffs);
					}

					// 部门
					SerInfoResponse departmentSir = HttpManager.execSerSql2(
							getString(R.string.url_exec_serSql), mobileID,
							"departmentsql", Constants.LOAD_MODEL_DEPARTMENT);
					if (departmentSir != null) {
						Department[] departments = (Department[]) departmentSir.os;

						mDB.insertDepartment(Arrays.asList(departments));
					}

					// 组
					SerInfoResponse workgroupSir = HttpManager.execSerSql2(
							getString(R.string.url_exec_serSql), mobileID,
							"workgroupsql", Constants.LOAD_MODEL_WORKGROUP);
					if (workgroupSir != null) {
						Position[] positions = (Position[]) workgroupSir.os;

						mDB.insertPosition(Arrays.asList(positions));
					}

					versionMap.put(Pref.KEY_CONTACT, version.contactVersion);
					mDB.insertVersion(versionMap);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

		}
	}

	public static int currentVersion = 1;
	private int serVersion;
	private static String strURL_APK = "";

	private boolean checkUpdate() {
		boolean needUpdate = false;
		int curVersion = currentVersion;
		// curVersion = getPackageManager().getPackageInfo(getPackageName(),
		// 0).versionCode);
		try {
			curVersion = getPackageManager()
					.getPackageInfo(getPackageName(), 0).versionCode;
			Log.e("----------update-----------", "----curVersion----"
					+ curVersion);
		} catch (NameNotFoundException e) {
		}
		serVersion = GetURL_VersionCode();
		// if (curVersion < serVersion && currentVersion < serVersion){
		if (curVersion < serVersion) {
			needUpdate = true;
		}

		return needUpdate;
	}

	private int GetURL_VersionCode() {
		int iVersionCode = currentVersion;
		try {
			JSONObject j = new JSONObject(HttpManager.push(
					"http://124.74.67.130:8080/Atp/version/version.action",
					false, null));
			iVersionCode = Integer.valueOf(j.getString("version"));
			String url = j.getString("url");
			strURL_APK = "http://124.74.67.130:8080/Atp/" + url;
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.e("----------update-----------", "----service Version----"
				+ iVersionCode);
		return iVersionCode;
	}

	public String getFileName(String path) {
		if (path == null)
			return "";
		return path.substring(path.lastIndexOf("/") + 1);
	}

	public boolean checkApkExist(String packageName) {

		PackageManager manager = getPackageManager();
		List<PackageInfo> pkgList = manager.getInstalledPackages(0);
		for (int i = 0; i < pkgList.size(); i++) {
			PackageInfo pI = pkgList.get(i);
			if (pI.packageName.equalsIgnoreCase(packageName))
				return true;
		}

		return false;
	}

}
